import ImgCrop from 'antd-img-crop';
import { Alert, Avatar, Button, message, Skeleton, Space, Upload, Image, Tooltip } from 'antd';
import type { UploadProps } from 'antd';
import React, { useEffect, useState } from 'react';
import { useIntl, useRequest } from 'umi';
import { getApiFileCenterConfigre as GetUploadConfigre } from "@/services/furion-cms/FileUpload";
import type { UploadFile, UploadChangeParam } from 'antd/lib/upload/interface';
import { UploadOutlined, UserOutlined } from '@ant-design/icons';
import type { CropperProps } from 'react-easy-crop';

interface CustomUploadProps {
  ren?: boolean;
  /** 裁剪图片 */
  crop?: boolean;
  aspect?: number;
  uploadProps?: UploadProps;
  cropperProps?: Partial<CropperProps>;
  fileValue?: any;
  /** 存放目录路径 格式: user/avatar/ */
  dir?: string;
  /** 上传完成后回调 */
  onFinish?: (results: UploadResult[]) => void;
}

type UploadResult = {
  uid: string;
  name: string;
  success: boolean;
  fileUri?: string;
  error?: string;
}

const CustomUpload: React.FC<CustomUploadProps> = (props) => {
  const { children, ren, crop, aspect, uploadProps, cropperProps, dir, onFinish } = props;

  const { data, error, loading } = useRequest(() => GetUploadConfigre({ dir }));

  if (loading) {
    return (<Skeleton.Button active={true} block />);
  }
  if (error) {
    return (<Alert message={error} type="error" showIcon />);
  }

  console.log('cropperProps', cropperProps)

  const changeHandle = (e: UploadChangeParam) => {
    console.log('CropUpload-onChange', e);
    uploadProps?.onChange?.(e);
    // 当文件列表都处理完成是才触发 onFinish
    if (e.fileList.every(f => f.status != 'uploading')) {
      const result: UploadResult[] = e.fileList.map(({ uid, name, status, response }) => {
        const success = status === 'done' ? response.success : status !== 'error';
        const errorMessage = status === 'error' ? '系统错误,请于管理员联系' : response.errorMessage;
        // e.file.response = errorMessage;

        return ({
          uid,
          name,
          success,
          fileUri: response.data,
          error: errorMessage
        })
      });

      onFinish?.(result);
    }
  }

  const dataHandle = (file: UploadFile) => {
    // 文件重命名
    const suffix = file.name.slice(file.name.lastIndexOf('.'));
    const filename = ren ? Date.now() + suffix : file.name;
    return {
      key: `${dir}${filename}`,
      dir,
      ...data?.extraData
    }
  }

  let defaultProps: UploadProps = {
    action: data?.host,
    data: dataHandle,
    headers: data?.headers,
    onChange: changeHandle
  };

  // 处理传入的初始化文件列表
  if (props.fileValue) {
    console.log('handleFileList', props.fileValue);
    let handleFileList: any[] = [];
    if (Array.isArray(props.fileValue)) {
      handleFileList = props.fileValue as string[];
    }
    else {
      handleFileList = [props.fileValue as string];
    }

    defaultProps.fileList = handleFileList.map((item, index) => ({
      uid: `-${index + 1}`,
      name: 'image.png',
      status: 'done',
      url: item
    }));
  }

  if (crop) {
    // TODO:当启用裁剪时只能单选
    defaultProps = {
      ...defaultProps,
      maxCount: 1,
      multiple: false
    }
  }

  const uploadDom = (<Upload {...uploadProps}
    {...defaultProps}>
    {children}
  </Upload>);

  return (
    crop ? (<ImgCrop fillColor='transparent'
      cropperProps={cropperProps}
      aspect={aspect}
      rotate>
      {uploadDom}
    </ImgCrop>) :
      uploadDom
  )

}

export default CustomUpload;

interface CommonUploadProps {
  src?: string;
  onChange?: (fileUri: string) => void;
  disabled?: boolean;
}

/**
 * 头像上传组件
 */
export const AvatarUpload: React.FC<CommonUploadProps & {
  aspect?: number;
  cropperProps?: Partial<CropperProps>;
}> = (props) => {
  /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
  const intl = useIntl();
  const [uploadLoading, setUploadLoading] = useState(false);

  return (<Space direction="vertical">
    <Avatar
      size={110}
      icon={<UserOutlined />}
      src={props.src}
      style={{
        marginBottom: 15
      }}
    />
    <CustomUpload dir="avatar/"
      uploadProps={{
        listType: 'picture',
        showUploadList: false,
        onChange: e => setUploadLoading(e.file.status === 'uploading'),
      }} onFinish={results => {
        if (Array.isArray(results) && results.length) {
          const uplodaResult = results[0];
          if (uplodaResult.success) {
            props.onChange?.(uplodaResult?.fileUri ?? '');
          }
          else {
            message.error(uplodaResult.error);
          }
        }
      }} cropperProps={props.cropperProps} aspect={props.aspect} crop ren>
      {props.disabled ? '' : <Button loading={uploadLoading} icon={<UploadOutlined />}>
        {props?.src ? intl.formatMessage({
          id: 'pages.user.detail.input.avatar.update',
          defaultMessage: '更换头像'
        }) : intl.formatMessage({
          id: 'pages.user.detail.input.avatar.add',
          defaultMessage: '上传头像'
        })}
      </Button>}
    </CustomUpload>
  </Space>)
}

interface ImagePerviewUploadProps extends CommonUploadProps {
  dir?: string;
  size?: number | string;
  crop?: boolean;
  aspect?: number;
  cropperProps?: Partial<CropperProps>;
}

export const ImagePerviewUpload: React.FC<ImagePerviewUploadProps> = (props) => {
  /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
  const intl = useIntl();
  const [uploadLoading, setUploadLoading] = useState(false);

  const defaultChildren = props?.src ? intl.formatMessage({
    id: 'pages.common.upload.img.change',
    defaultMessage: '更新图片'
  }) : intl.formatMessage({
    id: 'pages.common.upload.img',
    defaultMessage: '上传图片'
  });

  return (<Space direction="vertical">
    <Image
      width={props.size}
      src={props.src ?? ''}
      fallback=""
    />

    <CustomUpload dir={props.dir ?? 'img/'}
      uploadProps={{
        listType: 'picture',
        showUploadList: false,
        onChange: e => setUploadLoading(e.file.status === 'uploading'),
      }} onFinish={results => {
        if (Array.isArray(results) && results.length) {
          const uplodaResult = results[0];
          if (uplodaResult.success) {
            props.onChange?.(uplodaResult?.fileUri ?? '');
          }
          else {
            message.error(uplodaResult.error);
          }
        }
      }} cropperProps={props.cropperProps} aspect={props.aspect} crop={props.crop} ren>
      {props.disabled ? '' : <Button loading={uploadLoading} icon={<UploadOutlined />} block>
        {props.children ?? defaultChildren}
      </Button>}
    </CustomUpload>
  </Space>)
}

interface FileUploadProps extends CommonUploadProps {
  dir?: string;
  mini?: boolean;
  value?: string;
}

export const FileUpload: React.FC<FileUploadProps> = (props) => {
  /**
     * @en-US International configuration
     * @zh-CN 国际化配置
     * */
  const intl = useIntl();
  const [uploadLoading, setUploadLoading] = useState(false);
  const [extisUploadFile, setExtisUploadFile] = useState(false);

  useEffect(() => {
    setExtisUploadFile(props.value !== undefined);
  }, []);

  const defaultChildren = props?.src ? intl.formatMessage({
    id: 'pages.common.upload.file.change',
    defaultMessage: '更新文件'
  }) : intl.formatMessage({
    id: 'pages.common.upload.file',
    defaultMessage: '上传文件'
  });

  // 尝试获取传入的文件名称
  const fileName = props.value?.split('/').pop();

  return (<Space direction="vertical">
    <CustomUpload dir={props.dir ?? 'file/'}
      uploadProps={{
        onChange: e => setUploadLoading(e.file.status === 'uploading'),
        onRemove: () => {
          props.onChange?.('');
          setExtisUploadFile(false);
        },
        showUploadList: !props.mini,
        defaultFileList: props.value ? [{
          uid: '1',
          name: fileName!,
          status: 'done',
          url: props.value
        }] : []
      }} onFinish={results => {
        if (Array.isArray(results) && results.length) {
          const uplodaResult = results[0];
          if (uplodaResult.success) {
            props.onChange?.(uplodaResult?.fileUri ?? '');
            setExtisUploadFile(true);
          }
          else {
            message.error(uplodaResult.error);
          }
        }
      }} ren>
      {(props.disabled || extisUploadFile || uploadLoading) ? '' :
        (props.mini ? <Tooltip title="上传文件">
          <Button type="link" size="small" icon={<UploadOutlined />} loading={uploadLoading}
            style={{
              width: 16,
              height: 16,
              padding: 0
            }} />
        </Tooltip> :
          <Button loading={uploadLoading} icon={<UploadOutlined />} block>
            {props.children ?? defaultChildren}
          </Button>)
      }
    </CustomUpload>
  </Space>);
}